﻿using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Data;
using System.Windows.Media.Imaging;

namespace CPPEI.Coolzon.Designer.Views
{
    public class SceneIdToThumbnailConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            if(value == null)
            {
                return null;
            }

            FileInfo file = new FileInfo(ThumbnailHelper.GetThumbPath(value.ToString()));
            if (file != null && file.Exists)
            {
                BitmapImage refBitmapImage;
                using (FileStream fileStream = File.Open(file.FullName, FileMode.Open, FileAccess.Read))
                {
                    using (BinaryReader binReader = new BinaryReader(fileStream))
                    {
                        byte[] bytes = binReader.ReadBytes((int)file.Length);

                        refBitmapImage = new BitmapImage();
                        refBitmapImage.CacheOption = BitmapCacheOption.OnLoad;
                        refBitmapImage.CreateOptions = BitmapCreateOptions.IgnoreImageCache;
                        refBitmapImage.BeginInit();
                        refBitmapImage.StreamSource = new MemoryStream(bytes);
                        refBitmapImage.EndInit();
                    }
                }
                return refBitmapImage;
            }
            else
            {
                return null;
            }
                
        }

        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            return null;
        }
    }
}
